﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIController : MonoBehaviour
{

    [SerializeField] private Text healthLabel;
    [SerializeField] private InventoryPopup popup;
    [SerializeField] private Text levelEnding;

    void Awake()
    {
        //血量更新事件侦听器
        Messenger.AddListener(GameEvent.HEALTH_UPDATED,OnHealthUpdated);
        Messenger.AddListener(GameEvent.LEVEL_COMPLETE,OnLevelComplete);
        Messenger.AddListener(GameEvent.LEVEL_COMPLETE, OnLevelFailed);
        Messenger.AddListener(GameEvent.GAME_COMPLETE, OnGameComplete);
    }

	// Use this for initialization
	void Start () {
		OnHealthUpdated();

        popup.gameObject.SetActive(false);
	    levelEnding.gameObject.SetActive(false);
    }
	
	// Update is called once per frame
	void Update () {
	    if (Input.GetKeyDown(KeyCode.M))
	    {
	        bool isShowing = popup.gameObject.activeSelf;
            popup.gameObject.SetActive(!isShowing);
	        popup.Refresh();
	    }
	}

    void OnDestroy()
    {
        Messenger.RemoveListener(GameEvent.HEALTH_UPDATED,OnHealthUpdated);
        Messenger.RemoveListener(GameEvent.LEVEL_COMPLETE, OnLevelComplete);
        Messenger.RemoveListener(GameEvent.LEVEL_COMPLETE, OnLevelFailed);
        Messenger.RemoveListener(GameEvent.LEVEL_COMPLETE, OnGameComplete);
    }

    void OnHealthUpdated()
    {
        //事件侦听器更新Health函数
        string message = "Health:" + Manager.Player.health + "/" + Manager.Player.maxHealth;
        healthLabel.text = message;
    }

    void OnLevelComplete()
    {
        StartCoroutine(CompleteLevel());
    }

    IEnumerator CompleteLevel()
    {
        levelEnding.gameObject.SetActive(true);
        levelEnding.text = "Level1 Complete!";

        yield return  new WaitForSeconds(2);

        Manager.Mission.GoToNext();
    }

    private void OnLevelFailed()
    {
        StartCoroutine(FailLevel());
    }

    IEnumerator FailLevel()
    {
        levelEnding.gameObject.SetActive(true);
        levelEnding.text = "Level Failed";

        yield return new WaitForSeconds(2);

        Manager.Player.Respawn();
        Manager.Mission.RestartCurrent();
    }

    public void SaveGame()
    {
        Manager.Data.SaveGameState();
    }

    public void LoadGame()
    {
        Manager.Data.LoadGameState();
    }

    private void OnGameComplete()
    {
        levelEnding.gameObject.SetActive(true);
        levelEnding.text = "You Finished the Game!";
    }
}
